﻿$(function () {
    //initList();      
    grid.bind();
    //    setTimeout(
    //        $(window).resize(function () {
    //            var h = $(window).height() - 4;
    //            var w = $(window).width();
    //            using('datagrid', function () {
    //                $('#list').datagrid('resize', { width: w - 4, height: h - 40 });
    //            });
    //        }), 100);

    //    $('#a_edit').click(CRUD.edit);
    //    $('#a_delete').click(CRUD.del);
    AddUser(); //添加用户
    EditUser(); //编辑用户
    DeleteUser(); //删除用户
    SetUserPassword(); //设置用户密码

    $('#a_refresh').click(function () {
        $('#list').datagrid('reload');
    });

});

/* 方法一绑定数据
var initList = function () {
    var winSize = { width: $(window).width() - 4, height: $(window).height() - 40 };
    $('#list').datagrid({
        url: "handler/UserAdminHandler.ashx",
        title: "系统用户列表",
        iconCls: 'icon icon-list',
        width: winSize.width,
        height: winSize.height,
        nowrap: false, //折行
        rownumbers: true, //行号
        striped: true, //隔行变色
        idField: 'Id', //主键
        singleSelect: true, //单选
        checkOnSelect: true,
        frozenColumns: [[]],
        columns: [[
            { title: '主键', field: 'Id', hidden: true },
            { title: '编号', field: 'Code', width: 150 },
            { title: '登录名', field: 'UserName', width: 150, sortable: true },
            { title: '用户名', field: 'RealName', width: 150 },
            { title: '部门', field: 'DepartmentName', width: 150 },
            { title: '角色主键', field: 'RoleId', hidden: true },
            { title: '有效', field: 'Enabled', width: 50, formatter: imgcheckbox },
            { title: '邮箱地址', field: 'Email', width: 150 },
            { title: '手机号码', field: 'Mobile', width: 150 },
            { title: '描述', field: 'Description', width: 200 }
        ]]
    });
}
*/

var grid = {
    bind: function () {
        var winSize = { width: $(window).width() - 4, height: $(window).height() - 40 };
        $('#list').datagrid({
            url: "handler/UserAdminHandler.ashx",
            title: "系统用户列表",
            iconCls: 'icon icon-list',
            width: winSize.width,
            height: winSize.height,
            nowrap: true, //false:折行
            rownumbers: true, //行号
            striped: true, //隔行变色
            idField: 'Id', //主键
            singleSelect: true, //单选
            checkOnSelect: true,
            //frozenColumns: [[]],
            columns: [[
                    { title: '主键', field: 'Id', hidden: true },
                    { title: '编号', field: 'Code', width: 150 },
                    { title: '登录名', field: 'UserName', width: 150, sortable: true },
                    { title: '用户名', field: 'RealName', width: 150 },
                    { title: '部门', field: 'DepartmentName', width: 150 },
                    { title: '角色主键', field: 'RoleId', hidden: true },
                    { title: '有效', field: 'Enabled', width: 50, formatter: imgcheckbox },
                    { title: '邮箱地址', field: 'Email', width: 150 },
                    { title: '手机号码', field: 'Mobile', width: 150 },
                    { title: '描述', field: 'Description', width: 200 },
                    { title: 'Enabled', field: 'Enabled', hidden: true },
                    { title: 'Gender', field: 'Gender', hidden: true },
                    { title: 'UserPassword', field: 'UserPassword', hidden: true },
                    { title: 'Birthday', field: 'Birthday', formatter: date2str, hidden: true },
                    { title: 'Telephone', field: 'Telephone', width: 200, hidden: true },
                    { title: 'Duty', field: 'Duty', hidden: true },
                    { title: 'QICQ', field: 'QICQ', hidden: true },
                    { title: 'Title', field: 'Title', hidden: true },
                    { title: 'RoleId', field: 'RoleId', hidden: true },
                    { title: 'CompanyId', field: 'CompanyId', hidden: true },
                    { title: 'CompanyName', field: 'CompanyName', hidden: true },
                    { title: 'DepartmentId', field: 'DepartmentId', hidden: true },
                    { title: 'DepartmentName', field: 'DepartmentName', hidden: true },
                    { title: 'WorkgroupId', field: 'WorkgroupId', hidden: true },
                    { title: 'WorkgroupName', field: 'WorkgroupName', hidden: true },
                    { title: 'HomeAddress', field: 'HomeAddress', hidden: true }
                ]]
        });
    },
    getSelectedRow: function () {
        return $('#list').datagrid('getSelected');
    }
}

var imgcheckbox = function (cellvalue, options, rowObject) {
    return cellvalue ? '<img src="/css/icon/ok.png" alt="正常" title="正常" />' : '<img src="/css/icon/stop.png" alt="禁用" title="禁用" />';
}

var date2str = function (cellvalue, options, rowObject) {
    if (cellvalue)
        return $D(cellvalue).strftime("%Y-%m-%d");
    else
        return '';
}

var initUIform = function () {
    top.$('#w').hWindow({ html: pform, width: 640, height: 520, title: '添加用户', iconCls: 'icon-add', submit: function () {
        var flag = true;
        top.$('#uiform input').each(function () {
            if ($(this).attr('required') || $(this).attr('validType')) {
                if (!top.$(this).validatebox('isValid')) {
                    flag = false;
                    return;
                }
            }
        });

//        if (flag) {
            var vRoleId = top.$('#txtRoleId').combobox('getValue');
            var vCompanyId = top.$('#txtCompanyName').combobox('getValue');
            var vDepartmentId = top.$('#txtDepartmentName').combobox('getValue');
            var vWorkgroupId = top.$('#txtWorkgroupName').combobox('getValue');
            var vCompanyName = top.$('#txtCompanyName').combobox('getText');
            var vDepartmentName = top.$('#txtDepartmentName').combobox('getText');
            var vWorkgroupName = top.$('#txtWorkgroupName').combobox('getText');
            var queryString = top.$('#uiform').serialize() + '&action=add';
            queryString = queryString + '&vRoleId=' + vRoleId + '&vCompanyId=' + vCompanyId + '&vDepartmentId=' + vDepartmentId + '&vWorkgroupId=' + vWorkgroupId;
            queryString = queryString + '&vCompanyName=' + vCompanyName + '&vDepartmentName=' + vDepartmentName + '&vWorkgroupName=' + vWorkgroupName;
            $.ajaxtext('handler/UserAdminHandler.ashx', queryString, function (msg) {
                if (msg == "1") {
                    top.$('#notity').jnotifyAddMessage({ text: '添加成功.', permanent: false, type: 'message' });
                    top.$('#w').window('close');
                    $('#list').datagrid('reload');
                }
                else if (msg == "0") {
                    top.$('#notity').jnotifyAddMessage({ text: '用户名已存，请更换用户名.', permanent: false, type: 'warning' });
                    top.$('#txtUsername').select();
                    return false;
                }
                else {
                    alert(msg);
                }
            });
//        }
        return false;
    }
    });

    top.$('#uiform input').each(function () {
        if ($(this).attr('required') || $(this).attr('validType'))
            top.$(this).validatebox();
    });

    //top.$('#txtgroupid').combotree({ data: $('#w').data('treedata') });
    top.$('#txtBirthday').datebox();
}

var AddUser = function () {
    $('#a_add').click(function () {
        if ($(this).linkbutton('options').disabled == true) {
            return;
        }
        initUIform();
        //绑定各数据字典
        pubMethod.bindCategory('txtGender', 'Gender');
        pubMethod.bindCategory('txtRoleId', 'null');
        pubMethod.bindCategory('txtCompanyName', 'Company');
        pubMethod.bindCategory('txtDepartmentName', 'Department');
        pubMethod.bindCategory('txtWorkgroupName', 'Workgroup');
        top.$('#chkEnabled').attr("checked", true);
        top.$('#txtUserName').focus();
        top.$('#txtDescription').val("");
        //        top.$('#txtUsername').attr("disabled", false);
        //        top.$('#txtPassword').next().remove().end().show();
    });
}

var EditUser = function () {
    $('#a_edit').click(function () {
        if ($(this).linkbutton('options').disabled == true) {
            return;
        }

        var selectRow = grid.getSelectedRow();
        if (selectRow != null) {

            if (selectRow.UserName != '' && selectRow.UserName == 'Administrator' && curUserinfo.username != 'Administrator') {
                $.messager.alert('警告提示', '你不能修改超级管理员用户！', 'warning');
                return false;
            }

            //弹窗
            top.$('#w').hWindow({ html: pform, width: 640, height: 520, title: '修改用户', iconCls: 'icon-edit', submit: function () {
                var flag = true;
                top.$('#uiform input').each(function () {
                    if ($(this).attr('required') || $(this).attr('validType')) {
                        if (!top.$(this).validatebox('isValid')) {
                            flag = false;
                            return;
                        }
                    }
                });

                //                if (flag) {
                /*
                if (top.$('#chkdisabled').is(':checked') && ouser.uid == __c_uinfo.id) {
                alert('您不能禁用自己的帐户！');
                return false;
                }
                */

                var vRoleId = top.$('#txtRoleId').combobox('getValue');
                var vCompanyId = top.$('#txtCompanyName').combobox('getValue');
                var vDepartmentId = top.$('#txtDepartmentName').combobox('getValue');
                var vWorkgroupId = top.$('#txtWorkgroupName').combobox('getValue');
                var vCompanyName = top.$('#txtCompanyName').combobox('getText');
                var vDepartmentName = top.$('#txtDepartmentName').combobox('getText');
                var vWorkgroupName = top.$('#txtWorkgroupName').combobox('getText');

                var queryString = top.$('#uiform').serialize() + '&action=edit&id=' + selectRow.Id;
                queryString = queryString + '&vRoleId=' + vRoleId + '&vCompanyId=' + vCompanyId + '&vDepartmentId=' + vDepartmentId + '&vWorkgroupId=' + vWorkgroupId;
                queryString = queryString + '&vCompanyName=' + vCompanyName + '&vDepartmentName=' + vDepartmentName + '&vWorkgroupName=' + vWorkgroupName;
                $.ajaxtext('handler/UserAdminHandler.ashx', queryString, function (msg) {
                    if (msg == "1") {
                        top.$('#notity').jnotifyAddMessage({ text: '修改成功.', permanent: false, type: 'message' });
                        top.$('#w').window('close');
                        $('#list').datagrid('reload');
                    }
                    else
                        alert(msg);
                });
                //                }
                return false;
            }
            });

            top.$('#uiform input').each(function () {
                if ($(this).attr('required') || $(this).attr('validType'))
                    top.$(this).validatebox();
            });
            //绑定各数据字典
            pubMethod.bindCategory('txtGender', 'Gender');
            pubMethod.bindCategory('txtRoleId', 'null');
            pubMethod.bindCategory('txtCompanyName', 'Company');
            pubMethod.bindCategory('txtDepartmentName', 'Department');
            pubMethod.bindCategory('txtWorkgroupName', 'Workgroup');

            //初始化相关数据
            top.$('#txtUserName').val(selectRow.UserName);
            top.$('#txtRealName').val(selectRow.RealName);
            top.$('#txtCode').val(selectRow.Code);
            top.$('#txtUserPassword').after('******').remove();
            top.$('#txtGender').combobox('setValue', selectRow.Gender);
            top.$('#txtMobile').val(selectRow.Mobile);
            top.$('#txtBirthday').val(selectRow.Birthday);
            top.$('#txtTelephone').val(selectRow.Telephone);
            top.$('#txtDuty').val(selectRow.Duty);
            top.$('#txtQICQ').val(selectRow.QICQ);
            top.$('#txtTitle').val(selectRow.Title);
            top.$('#txtEmail').val(selectRow.Email);
            top.$('#txtRoleId').combobox('setValue', selectRow.RoleId);
            top.$('#txtCompanyName').combobox('setValue', selectRow.CompanyId);
            top.$('#txtDepartmentName').combobox('setValue', selectRow.DepartmentId);
            top.$('#txtWorkgroupName').combobox('setValue', selectRow.WorkgroupId);
            //            top.$('#txtCompanyName').val(selectRow.CompanyName);
            //            top.$('#txtDepartmentName').val(selectRow.DepartmentName);
            //            top.$('#txtWorkgroupName').val(selectRow.WorkgroupName);
            top.$('#txtHomeAddress').val(selectRow.HomeAddress);
            top.$('#txtDescription').val(selectRow.Description);
            top.$('#chkEnabled').attr("checked", selectRow.Enabled == "1");
        } else {
            top.$('#notity').jnotifyAddMessage({ text: '请选择要修改的用户.', permanent: false, type: 'warning' });
            return false;
        }
    });
}

var DeleteUser = function () {
    $('#a_delete').click(function () {
        if ($(this).linkbutton('options').disabled == true) {
            return;
        }
        var selectRow = grid.getSelectedRow();

        if (selectRow) {
            if (selectRow.Id != '' && selectRow.Id == curUserinfo.id) {
                $.messager.alert('警告提示', '不能删除当前登录用户！', 'warning');
                return false;
            }

            if(selectRow.UserName != '' && selectRow.UserName == 'Administrator')
            {
                $.messager.alert('警告提示', '不能删除超级管理员用户！', 'warning');
                return false;
            }

            $.messager.confirm('询问提示', '确认要删除所选用户吗？', function (data) {
                if (data) {                    
                    $.ajaxtext('handler/UserAdminHandler.ashx', 'action=delete&id=' + selectRow.Id, function (msg) {
                        if (msg == '1') {
                            $.messager.alert('成功提示', '所选用户删除成功！');
                            $('#list').datagrid('reload');
                        } else {
                            $.messager.alert('错误提示', msg, 'error');
                        }
                    });
                }
            });
        }
        else {
            top.$('#notity').jnotifyAddMessage({ text: '请选择要删除的用户。', permanent: false, type: 'warning' });
            return;
        }
    });
}

var SetUserPassword = function () {
    $('#a_editpassword').click(function () {
        if ($(this).linkbutton('options').disabled == true) {
            return;
        }
        var selectRow = grid.getSelectedRow();
        if (selectRow != null) {
            top.$('#d').hDialog({ width: 300, height: 160, title: '设置用户密码', iconCls: 'icon-key', html: formeditpass, submit: function () {
                if (top.$('#txtNewPassword').validatebox('isValid')) {
                    $.ajaxtext('handler/UserAdminHandler.ashx', "action=setpassword&id=" + selectRow.Id + '&password=' + top.$('#txtNewPassword').val(), function (msg) {
                        if (msg == "1") {
                            top.$('#notity').jnotifyAddMessage({ text: '密码修改成功！请牢记新密码。', permanent: false, type: 'warning' });
                            top.$('#d').dialog('close');
                        } else
                            alert(msg);
                    })
                }
            }
            });

        top.$('#loginname').text(selectRow.UserName + ' | ' + selectRow.RealName);
            top.$('#txtNewPassword').validatebox();
        } else {
            top.$('#notity').jnotifyAddMessage({ text: '请选择要修改密码的用户。', permanent: false, type: 'warning' });
            return false;
        }
    });
}

//公共方法
var pubMethod = {
    bindCategory: function (categoryControl, categoryCode) {
        if (categoryControl == '' || categoryCode == '') {
            return;
        }

        if (categoryControl == 'txtGender') {
            top.$('#' + categoryControl).combobox({
                url: 'Modules/handler/DataItemAdminHandler.ashx?action=GetCategory&categorycode=' + categoryCode,
                method: 'get',
                valueField: 'ItemValue',
                textField: 'ItemName',
                editable: false,
                panelHeight: 'auto'
            });
        }

        if (categoryControl == 'txtRoleId') {
            top.$('#' + categoryControl).combobox({
                url: 'Modules/handler/RoleAdminHandler.ashx?action=GetEnabledRoleList',
                method: 'get',
                valueField: 'Id',
                textField: 'RealName',
                editable: false,
                panelHeight: 'auto'
            });
        }

        if (categoryControl == 'txtCompanyName' || categoryControl == 'txtDepartmentName' || categoryControl == 'txtWorkgroupName') {
            top.$('#' + categoryControl).combobox({
                url: 'Modules/handler/OrganizeAdminHander.ashx?action=GetOrganizeByCategory&OrganizeCategory=' + categoryCode,
                method: 'get',
                valueField: 'Id',
                textField: 'FullName',
                editable: false,
                panelHeight: 'auto'
            });
        }
    }  
}

var pform = '<form id="uiform"><table  cellpadding=5 cellspacing=0 width=100% align="center" class="grid2" border=0><tr><td align="right">';
    pform += '登录用户名：</td><td><input name="UserName" id="txtUserName" validType="length[2,40]" required="true" type="text" class="txt03" ></td><td align="right">';
    pform += '姓名：</td><td><input name="RealName" id="txtRealName" validType="length[2,40]" required="true" type="text" class="txt03" ></td></tr><tr><td align="right">';
    pform += '编号：</td><td><input name="Code" id="txtCode" validType="length[2,40]" type="text" class="txt03" ></td><td align="right">';
    pform += '用户密码：</td><td><input validType="safepass"  required="true" name="UserPassword" id="txtUserPassword"  type="password" class="txt03" ></td></tr><tr><td align="right">';
    pform += '性别：</td><td><input name="Gender" id="txtGender"  required="true" type="text" class="txt03" ></td><td align="right">';
    pform += '手机号码：</td><td><input name="Mobile" id="txtMobile" type="text" class="txt03" ></td></tr><tr><td align="right">';
    pform += '出生日期：</td><td><input name="Birthday" id="txtBirthday" type="text" class="txt03" ></td><td align="right">';
    pform += '固定电话：</td><td><input name="Telephone" id="txtTelephone" type="text" class="txt03" ></td></tr><tr><td align="right">';
    pform += '岗位：</td><td><input name="Duty" id="txtDuty" type="text" class="txt03" ></td><td align="right">';
    pform += 'QQ号码：</td><td><input name="QICQ" id="txtQICQ" type="text" class="txt03" ></td></tr><tr><td align="right">';
    pform += '职称：</td><td><input name="Title" id="txtTitle" type="text" class="txt03" ></td><td align="right">';
    pform += '邮箱地址：</td><td><input name="Email" id="txtEmail" type="text" class="txt03" ></td></tr><tr><td align="right">';
    pform += '默认角色：</td><td><input name="RoleId" id="txtRoleId" type="text" class="txt03" ></td><td align="right">';
    pform += '公司名称：</td><td><input name="CompanyName" id="txtCompanyName" type="text" class="txt03" ></td></tr><tr><td align="right">';
    pform += '部门名称：</td><td><input name="DepartmentName" id="txtDepartmentName" type="text" class="txt03" ></td><td align="right">';
    pform += '工作组：</td><td><input name="WorkgroupName" id="txtWorkgroupName" type="text" class="txt03" ></td></tr><tr><td align="right">';
    pform += '家庭地址：</td><td  colspan="3"><input name="HomeAddress" style="width:470px;" id="txtHomeAddress" type="text" class="txt03" ></td></tr><tr><td align="right">';
    pform += '有效性：</td><td colspan="3"><input id="chkEnabled" type="checkbox" name="Enabled" /><label>有效</label>&nbsp;&nbsp;<span style="color:#666;padding-left:20px;">注：用户无效（禁用该用户）后，该用户将不能登录。</span></td></tr><tr><td align="right"> ';
    pform += '描述：</td><td colspan =3><textarea  id="txtDescription" name="Description" rows="3" style="width:470px;height:50px;" class="txt03"></td></tr></table></form>';

var formeditpass = '<table class="grid" id="epform">';
    formeditpass += '<tr><td>登录名：</td><td><span id="loginname"></span></td></tr>';
    formeditpass += '<tr><td>新密码：</td><td><input  validType="safepass"  required="true" id="txtNewPassword" name="password" type="password" class="txt03" /></td></tr>';
    formeditpass += '</table>';